//
//  AppDelegate.m
//  ChatForHot
//
//  Created by FLY on 2018/10/8.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "AppDelegate.h"
#import "RegisterOrLoginViewController.h"
#import "RegisterInfoViewController.h"
#import <UMCommon/UMCommon.h>
#import <UMCAnalytics/UMAnalytics/MobClick.h>
#import "JPUSHService.h"
#import <UserNotifications/UserNotifications.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    APPINFO *appInfo = [APPINFO  defaultManager];
    [appInfo HOTCHATreset];
    [[DBUtility sharedbUtility] applicationLauching];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    application.applicationIconBadgeNumber = 0;
    
    EMOptions *options = [EMOptions optionsWithAppkey:HOTCHATEMAPPKEY];
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    
    //UM//
    [UMConfigure initWithAppkey:HOTCHATUMAPPKEY channel:appInfo.channelId];
    [UMConfigure setLogEnabled:YES];
    [MobClick setScenarioType:E_UM_NORMAL];
    //JPUSH
    [self HOTCHATconfigJPUSH:launchOptions];
    ///facebook//
    [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    
    if (appInfo.registerFlag == -2) {
        //no register
        RegisterOrLoginViewController *VC = [[RegisterOrLoginViewController alloc]init];
        self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:VC];
        [self.window makeKeyAndVisible];
    }else if (appInfo.registerFlag == 1){
        //no headpic
        RegisterInfoViewController *VC = [[RegisterInfoViewController alloc]init];
        self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:VC];
        [self.window makeKeyAndVisible];
    }
    else{
        
        [self initTabbarMenu];
    }

    return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [FBSDKAppEvents activateApp];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)initTabbarMenu{
    
    self.TabbarMenu = [[TabbarController alloc] init];
    self.window.rootViewController = self.TabbarMenu;
    [self.window makeKeyAndVisible];
}
- (void)HOTCHATconfigJPUSH:(NSDictionary *)launchOptions{
    
    BOOL isPro = YES;
    
#if DEBUG
    isPro = NO;
#else
    [JPUSHService setLogOFF];
#endif
    //Required
    //notice: 3.0.0 及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义 categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    // Required
    // init Push
    // notice: 2.1.5 版本的 SDK 新增的注册方法，改成可上报 IDFA，如果没有使用 IDFA 直接传 nil
    // 如需继续使用 pushConfig.plist 文件声明 appKey 等配置内容，请依旧使用 [JPUSHService setupWithOption:launchOptions] 方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:HOTCHATJPUSHAPPKEY
                          channel:HOTCHATAPPINFO.appid
                 apsForProduction:isPro];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
    
}
#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler NS_AVAILABLE_IOS(10_0){
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
////    [self receivePush:userInfo log:1];
//
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
//
    completionHandler(UNNotificationPresentationOptionSound);// 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
#pragma clang diagnostic ignored "-Wstrict-prototypes"
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler NS_AVAILABLE_IOS(10_0){
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
//    [self receivePush:userInfo log:2];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
//    [self receivePush:userInfo log:3];
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
//    [self receivePush:userInfo log:4];
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    
    if (@available(iOS 9.0, *)) {
        BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
                                                                      openURL:url
                                                            sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                                                                   annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
                        ];
        // Add any custom logic here.
        return handled;
    } else {
        // Fallback on earlier versions
        return NO;
    }
}


@end
